import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import { AtTabs, AtTabsPane } from 'taro-ui';
import Taro, { useDidShow } from '@tarojs/taro';
import { debounce } from '@/utils/helper';
import utils from '@/utils/index';
import EmptyTip from '@/components/EmptyTip';
import Advert from '@/components/Advert';
import Imagelocation from '@/components/Imagelocation';
import pStar from '@/images/taihuHomePage/star.png';
import pTuancanbiaoqian from '@/images/common/tuancanbiaoqian.png';
import pNotice from '@/images/common/notice.png';
import './index.scss';
import StandServiceTags from '../../components/StandServiceTags';

const ShopListPage = ({
  dispatch,
  shopListClassifyParams = {},
  takeOutOrgList = [],
  takeOutOrgFinished = false,
  secondIndustryList = [],
}) => {
  const [curLocation, setCurLocation] = useState(null);
  const [currentTab, setCurrentTab] = useState(0);

  const showNextPage = debounce(() => {
    !takeOutOrgFinished && getTakeOutOrgList();
  }, 200);

  useDidShow(() => {
    if (shopListClassifyParams.text) {
      Taro.setNavigationBarTitle({
        title: shopListClassifyParams.text,
      });
    }
  });

  useEffect(() => {
    getSecondIndustry();
    getLocation();
  }, []);

  useEffect(() => {
    curLocation && getTakeOutOrgList();
  }, [curLocation, currentTab]);

  const getSecondIndustry = () => {
    dispatch({
      type: 'otherApi/getSecondIndustryModel',
      payload: {
        firstIndustryId: shopListClassifyParams.firstIndustryId,
      },
    });
  };

  const getTakeOutOrgList = () => {
    const { latitude, longitude } = curLocation;
    dispatch({
      type: 'takeOut/getTakeOutItemOrgListModel',
      payload: {
        isLocal: 1,
        firstIndustryId: shopListClassifyParams.firstIndustryId,
        secondIndustryId:
          secondIndustryList.length == 0 || secondIndustryList[currentTab].secondIndustryId == '0'
            ? undefined
            : secondIndustryList[currentTab].secondIndustryId,
        pageSize: 20,
        lat: latitude,
        lon: longitude,
      },
    });
  };

  const getLocation = async () => {
    let localLocation = utils.getLocalEffectLocation();
    if (localLocation) {
      const { latitude, longitude } = localLocation;
      setCurLocation({ latitude, longitude });
    } else {
      Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        timeout: 5000,
        success: (res) => {
          const { latitude, longitude } = res;
          const timeStamp = new Date().getTime();
          setCurLocation({ latitude, longitude });
          utils.setLocalStorage('location', { latitude, longitude, timeStamp });
        },
        fail: () => {
          setCurLocation({ latitude: undefined, longitude: undefined });
        },
      });
    }
  };

  const handleTabChanged = (index) => {
    if (index !== currentTab) {
      setCurrentTab(index);
      dispatch({
        type: 'takeOut/setTakeOutItemList',
        payload: {
          takeOutItemOrgList: [],
        },
      });
    }
  };

  return (
    <View className="totalPage_storeList">
      <ScrollView
        className="contentPage"
        scrollY
        lowerThreshold={340}
        onScrollToLower={showNextPage}
      >
        <Advert alias={'_industry' + shopListClassifyParams.firstIndustryId} className="advert" />

        {secondIndustryList.length > 1 && (
          <AtTabs
            className="industryAtTabs"
            current={currentTab}
            tabList={secondIndustryList}
            onClick={handleTabChanged}
            scroll={secondIndustryList.length > 4 ? true : false}
            key={'AtTabs_' + Math.random()}
          >
            {secondIndustryList.length > 0 &&
              secondIndustryList.map((item, index) => (
                <AtTabsPane current={currentTab} index={index} key={'AtTabsPane_' + Math.random()}>
                  <LocalOrg dataList={takeOutOrgList} key={'industryAtTabsPane_' + index} />
                </AtTabsPane>
              ))}
          </AtTabs>
        )}

        {takeOutOrgFinished && takeOutOrgList.length > 8 && (
          <View className="end">- 我是有底线的 -</View>
        )}
        {takeOutOrgFinished && takeOutOrgList.length == 0 && <EmptyTip type="noShop" />}
      </ScrollView>
    </View>
  );
};

const LocalOrg = ({ dataList = [] }) => {
  const goShopDetail = (shopId) => {
    let url = '/mainSubPack/shopInfo/index?orgId=' + shopId;
    Taro.navigateTo({
      url,
    });
  };
  console.log('dataList', dataList);
  return (
    <View className="storeList">
      {dataList.length > 0 &&
        dataList.map((shop) => (
          <View
            className="shop localOrg"
            key={'slocalOrgShop' + shop.id}
            onClick={() => goShopDetail(shop.id)}
          >
            {shop.activityList &&
              shop.activityList.length > 0 &&
              shop.activityList.map((activity, idx) => {
                let src = '';
                if (activity.type == 1) {
                  //团餐
                  src = pTuancanbiaoqian;
                }
                if (activity.isShow == 1) {
                  return <Image className="tcIcon" src={src} key={'slocalOrgActivity' + idx} />;
                } else {
                  return null;
                }
              })}
            <View className="left">
              <Imagelocation className="shopIcon" src={shop.logo} type="shop" />
            </View>
            <View className="right">
              <View className="name">{shop.name}</View>
              <View className="info">
                <View className="infoLeft">
                  <Image
                    className="starIcon"
                    src={typeof shop.grade !== 'undefined' ? pStar : ''}
                  />
                  <Text className="starNum">{shop.grade || ''}</Text>
                </View>
                <View className="infoRight">
                  <Text className="distance">
                    {typeof shop.distance !== 'undefined' ? shop.distance + 'km' : ''}
                  </Text>
                </View>
              </View>

              <StandServiceTags className="tags" serviceTags={shop.serviceTags} />

              <View className="industry">{shop.secondIndustryName || ''}</View>
              <View className="notice">
                {shop.notice && shop.notice.length > 0 && (
                  <>
                    <Text>店铺</Text>
                    <Image className="noticeIcon" src={pNotice} />
                    <Text>：{shop.notice}</Text>
                  </>
                )}
              </View>
              {shop.policy && shop.policy.length > 0 && (
                <View className="manjianLine">
                  {shop.policy.map((item, index) => (
                    <Text className="manjian" key={'slocalOrgManjian' + index}>
                      {item}
                    </Text>
                  ))}
                </View>
              )}
            </View>
          </View>
        ))}
    </View>
  );
};

export default connect(({ otherApi, takeOut }) => ({
  shopListClassifyParams: otherApi.shopListClassifyParams,
  takeOutOrgList: takeOut.takeOutItemOrgList,
  takeOutOrgFinished: takeOut.takeOutItemOrgFinished,
  secondIndustryList: otherApi.secondIndustryList,
}))(ShopListPage);
